<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Console\Commands;

use App\Services\CosService;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;

class DbBak extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:bak';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '备份数据库';

    protected $process;

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(CosService $cosService)
    {
        if (env('APP_ENV') != 'production') {
            return 0;
        }
        try {
            $this->process = new Process(['/home/work/script/bak_db.sh']);
            $this->process->mustRun();
            $filepath = '/data/jingyao-data/temp/db_bak/jy.sql';
            $fp = fopen($filepath, 'a+');
            $file = fread($fp, filesize($filepath));
            fclose($fp);
            $cosDir = '/db_bak/' . date('Y-m-d') . '/jy.sql';
            $cosService->uploadFileNormal($cosDir, $file);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
            return 1;
        }
        $this->info('save db bak successfully');
        return 0;
    }
}
